package com.start.cas;

import com.start.common.api.Result;
import com.start.common.details.BaseUserDetails;
import com.start.common.entity.StartBaseUser;
import com.start.common.exceptions.StartBusException;
import com.start.common.user.StartUserInfoLoadService;
import com.start.security.StartTokenTools;
import com.start.security.annotations.IgnoreAuth;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Tag(name = "StartCasApi")
@RestController
@RequestMapping("/start/casApi")
public class StartCasApiController {
    @Autowired
    private StartClientService startClientService;
    @Autowired
    private StartTokenTools startTokenTools;

    @IgnoreAuth
    @CrossOrigin(origins = "*")
   @Operation(summary = "根据用户token获取用户信息")
    @GetMapping("/getUserInfoByToken/{appId}/{appSecret}/{token}/{timeMillis}/{sing}")
    public Result<?> getUserInfoByToken(@PathVariable("appId") String appId,
                                        @PathVariable("appSecret") String appSecret,
                                        @PathVariable("token") String token,
                                        @PathVariable("timeMillis") String timeMillis,
                                        @PathVariable("sing") String sing) {
        if (StringUtils.isAllBlank(appId)) {
            throw new StartBusException("appId is not empty");
        }
        if (StringUtils.isAllBlank(appSecret)) {
            throw new StartBusException("appSecret is not appSecret");
        }
        if (StringUtils.isAllBlank(token)) {
            throw new StartBusException("token is not appSecret");
        }
        if (StringUtils.isAllBlank(timeMillis)) {
            throw new StartBusException("timeMillis is not appSecret");
        }
        if (StringUtils.isAllBlank(sing)) {
            throw new StartBusException("sing is not appSecret");
        }
        if (!startClientService.hasClient(appId)) {
            throw new StartBusException("unknown appId");
        }
        if (!startClientService.checkSignature(appId, appSecret, token, timeMillis, sing, null)) {
            throw new StartBusException("signature error");
        }
        BaseUserDetails userDetails = startTokenTools.getUserDetailsByToken(token);
        if (userDetails == null) {
            throw new StartBusException("invalid token");
        }
        StartBaseUser baseUser = StartUserInfoLoadService.getInstance().getUserById(userDetails.getStartUserType(), userDetails.getUserId());
        if (baseUser == null) {
            throw new StartBusException("invalid token");
        }
        return Result.ok(CasUserInfo.created(baseUser));
    }
}
